package per.ace.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

public class FirstServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //服务端输出接受的信息
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println(System.currentTimeMillis() + ":server read data --> " + byteBuf.toString(Charset.forName("utf-8")));

        //回复数据到客户端
        System.out.println("server回复数据");
        ByteBuf out = getByteBuf(ctx);
        ctx.channel().writeAndFlush(out);


    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        byte[] bytes = "server return message".getBytes(Charset.forName("utf-8"));

        ByteBuf buffer = ctx.alloc().buffer();

        buffer.writeBytes(bytes);

        return buffer;
    }
}
